<template>
  <div style="padding-right: 8px" @click="handleSearchClick()">
    <van-search
      :value="searchVal"
      placeholder="请输入用户标签搜索"
      :disabled="true"
    >
      <!-- <div slot="action" @click="handleSearch" style="margin-left: 6px;">搜索</div> -->
    </van-search>
  </div>
  <van-cell center title="智能匹配">
    <template #right-icon>
      <van-switch
        :checked="isMatchMode"
        size="24px"
        @change="changeSwitch($event)"

      />
    </template>
  </van-cell>
  <matchUser
    v-if="isMatchMode === true"
    :user-info="userInfo"
    :loading="matchLoading"
    @againMatch="getHearUser1(1)"
    @inviteTeammate="handleInvite(userInfo.id)"
  ></matchUser>
  <userCardList
    v-else
    :user-list="userList"
    :loading="loading"
    @getMore="getMore"
    @invite="handleInvite"
  ></userCardList>

  <van-empty
    v-if="!userList || userList.length < 1"
    image="search"
    description="数据为空"
  />
  <van-popup
    :show="showPopop"
    round
    position="bottom"
    custom-style="height: 50%"
    @close="closePopup"
  >
    <van-radio-group :value="selectTeamOne" @change="selectTeam">
      <van-cell-group>
        <van-cell
          size="large"
          :title="`队伍${index + 1}：` + item.name"
          clickable
          data-name="1"
          v-for="(item, index) in teamList"
          :key="item.id"
        >
          <van-radio slot="right-icon" :name="item.id" />
        </van-cell>
      </van-cell-group>
    </van-radio-group>

    <div class="btn-pop">
      <van-button type="info" block round @click="confirmInvite"
        >确定邀请</van-button
      >
    </div>
  </van-popup>
  <van-notify id="van-notify" />

  <!-- <van-cell center title="心动模式">
    <template #right-icon>
      <van-switch
        v-model="isMatchMode"
        size="24"
        @change="changeSwitch($event)"
      />
    </template>
  </van-cell> -->
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'

import { recommendUser, getHearUser } from '../../api/user/userApi'
import userCardList from '../../components/userCardList.vue'
import matchUser from '../../components/matchUser.vue'
import { debounce, throttle } from '../../utils/tool.js'
import { hasCreatedTeam, sendMsg } from '../../api/team/team'
import useStore from '../../store'


const loading = ref(true)
const matchLoading = ref(true)
const isMatchMode = ref(false) //匹配模式，true-->>心动模式，false-->>普通模式</boolean>
const searchVal = ref('') //搜索值
const scrollHeight = ref(54)
const pageNum = ref(1)
const pageSize = ref(10)
let userList = ref([])
let userInfo = ref({})
let showPopop = ref(false)
const teamList = ref([]) //已经创建的队伍列表
let selectTeamOne = ref() //选中一个队伍
let selectUserOne = ref() //选中一个用户
let maxPage=ref(0)

const onChangeSearch = (e) => {
  searchVal.value = e.detail
}
const handleSearchClick = () => {
  console.log(11)

  uni.navigateTo({ url: '/pagePerson/user/search' })
}
const onSearch = () => {
  console.log(searchVal.value)
}
const getRecommendUser = async (pageNum, pageSize) => {
  const res = await recommendUser(pageNum, pageSize)
  userList.value = res.data.records
  maxPage.value=res.data.pages
  userList.value?.forEach((item) => {
    item.tags = JSON.parse(item.tags)
  })
  loading.value = false
  console.log(userList)
}

//智能匹配
const getHearUser1 = async (num) => {
  const res = await getHearUser(num)
  console.log(res)
  selectUserOne.value=res.data[0].id
  matchLoading.value = false
  if (res.code === 1) {
    isMatchMode.value = false
    matchLoading.value = true
    uni.showToast({
      title: res.message,
      icon: 'none',
      duration: 3000,
    })
    console.log(matchLoading.value, isMatchMode.value)

    return
  }
  userInfo.value = res.data[0]
  userInfo.value.tags = JSON.parse(res.data[0].tags)
  console.log(userInfo)
}
const changeSwitch = (e) => {
  if (uni.getStorageSync('Authorization') === null) {
    uni.showToast({
      title: '请登录',
      icon: 'none',
    })
    uni.switchTab({
      url: '/pages/person/person',
    })
    return false
  }
  console.log(e)

  isMatchMode.value = e.detail
  if (isMatchMode.value) {
    getHearUser1(1)
  } else {
    pageNum.value = 1
    getRecommendUser(pageNum.value, pageSize.value)
    matchLoading.value = true
  }
}
//关闭弹出窗
const closePopup = () => {
  showPopop.value = false
}
//邀请组队
const handleInvite = (e) => {
  if (uni.getStorageSync('Authorization') === null) {
    uni.showToast({
      title: '请登录',
      icon: 'none',
    })
    uni.switchTab({
      url: '/pages/person/person',
    })
    return false
  }
  console.log(e)
  selectUserOne.value = e
  showPopop.value = true
  getHasCreatedTeam()
}
//获取已经创建的队伍
const getHasCreatedTeam = async () => {
  const res = await hasCreatedTeam()
  console.log(res)
  
  teamList.value = res.data.teamUserVOList
  selectTeamOne.value = teamList.value[0].id
}
//选中队伍
const selectTeam = (e) => {
  console.log(e)
  selectTeamOne.value=e.detail
}
//确定邀请
const confirmInvite = async () => {
  if(teamList.value===null||teamList.value<=0){
    showPopop.value = false
    uni.showToast({
      title:'队伍为空，请先创建队伍',
      icon:'none',
      duration:2000
    })
    return
  }
  const obj={
    userId:selectUserOne.value ,
    teamId:selectTeamOne.value ,
  }
 const res=await useStore().team().sendInvitation(obj)
 console.log(res);
 if(res.code===0){
  uni.showToast({
  title:'发送成功',
  icon:'success',
  success:()=>{
    closePopup()
  }

 })
 }else{
  uni.showToast({
  title:'发送失败:'+res.description,
  icon:'none',
  success:()=>{
    closePopup()
  }

 })
 }
 
  // uni.requestSubscribeMessage({
  //   tmplIds: ['lZH_Sb4eub8CNfw3EoEJ2PaJAQOG2u7jvTrCL0U7TwM'],
  //   success: async (res) => {
  //     console.log('订阅授权', res)
  //     console.log('userId:' + selectUserOne.value)

  //     const sendRes = await sendMsg(selectUserOne.value, selectTeamOne.value)
  //     console.log(sendRes)
  //   },
  // })
}
onMounted(() => {
  getRecommendUser(pageNum.value, pageSize.value)

  // const instance = getCurrentInstance(); // 获取组件实例

  // const query = uni.createSelectorQuery().in(instance);
  // console.log(query);
  // query
  // .select(".vant-search")
  // .boundingClientRect((data) => {
  //   console.log(data.height);
  //   scrollHeight.value=data.height
  // })
  // .exec();
})
//触底加载
const getMore1 = async () => {
  console.log(maxPage.value);
  if(pageNum.value>=maxPage.value){
    return uni.showToast({
      title:'到底了',
      icon:'none'
    })
  }
  console.log('到底了')
  pageNum.value++
  console.log(pageNum.value)
  const res = await recommendUser(pageNum.value, pageSize.value)
  console.log(res.data.records)
  let resArr = res.data.records
  console.log(resArr)
  resArr?.forEach((item) => {
    item.tags = JSON.parse(item.tags)
  })
  userList.value = [...userList.value, ...resArr]
  console.log(userList.value)


  //  userList.value=userList.value.push(res.data.records)
}
//节流
const getMore = throttle(getMore1, 1000)
</script>
<style scoped>
.btn-pop {
  position: fixed;
  bottom: 6px;
  left: 8px;
  width: calc(100% - 16px);
}
</style>
